﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Shatter;

public class FruitMouseSplit : MonoBehaviour {
    Camera m_camera
    {
        get
        {
            return FreshFruitSceneController.Instance.currentCamera;
        }

    }

    bool Islock;

    public FruitMouseSplit SetLock(bool fsc)
    {
        Islock = fsc;
        return this;
    }

    public FruitMouseSplit SetManager(FruitShala fsc)
    {
        manager = fsc;
        return this;
    }

    FruitShala manager;

    public ShatterScheduler scheduler = null;

    public int raycastCount = 5;

    private bool started = false;
    private Vector3 start, end;

    public void Update()
    {
        if (Islock) return;
        if (Input.GetMouseButtonDown(0))
        {
            start = Input.mousePosition;

            started = true;
        }

        if (Input.GetMouseButtonUp(0) && started)
        {
            end = Input.mousePosition;

            // Calculate the world-space line

            float near = m_camera.nearClipPlane;

            Vector3 line = m_camera.ScreenToWorldPoint(new Vector3(end.x, end.y, near)) - m_camera.ScreenToWorldPoint(new Vector3(start.x, start.y, near));

            // Find game objects to split by raycasting at points along the line
            for (int i = 0; i < raycastCount; i++)
            {
                Ray ray = m_camera.ScreenPointToRay(Vector3.Lerp(start, end, (float)i / raycastCount));

                RaycastHit hit;

                if (Physics.Raycast(ray, out hit))
                {
                    Plane splitPlane = new Plane(Vector3.Normalize(Vector3.Cross(line, ray.direction)), hit.point);

                    if (scheduler != null)
                    {
                        scheduler.AddTask(new SplitTask(hit.collider.gameObject, new Plane[] { splitPlane }));
                    }
                    else
                    {
                        //hit.collider.SendMessage("Split", new Plane[] { splitPlane }, SendMessageOptions.DontRequireReceiver);
                        if (hit.transform.GetComponent<ShatterTool>() != null)
                            if (manager != null) { manager.SliceFruit(hit, splitPlane);/* manager._timerstampUpdate();*/ }
                    }
                }
            }

            started = false;
        }
    }
}
